package com.totem.base.filter;

import com.totem.base.CacheHolder;
import com.totem.base.SpringContextHolder;
import com.totem.base.constants.CacheConstants;
import com.totem.base.constants.ErrorCode;
import com.totem.base.exception.BaseException;
import com.totem.base.mybatis.UserIdContext;
import com.totem.base.model.Principal;
import com.totem.base.util.FilterUtil;
import com.totem.base.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

@Slf4j
public class AuthenticationFilter extends OncePerRequestFilter {
    private static final AntPathMatcher ignoresMatch = new AntPathMatcher();
    protected Set<String> ignores = Set.of(
            "/",
            "/swagger-ui.html",
            "/swagger-ui/",
            "/doc.html",
            "/favicon.ico",
            "/**/*.html",
            "/**/*.css",
            "/**/*.js",
            "/swagger-resources/**",
            "/v3/api-docs/**",
            "/admin/config/system",
            "/admin/code/verification",
            "/admin/code/verification/check",
            "/customer/create",
            "/customer/password/reset",
            "/customer/register/check",
            "/order/recharge",
            "/admin/test/**",
            "/admin/product/upload/file/**",
            "/admin/information/upload/file/**"
    );

    private HandlerExceptionResolver resolver;
    private CacheHolder cacheHolder;

    @Override
    protected void initFilterBean() throws ServletException {
        ApplicationContext ctx = SpringContextHolder.getApplicationContext();
        resolver = ctx.getBean("handlerExceptionResolver", HandlerExceptionResolver.class);
        cacheHolder = ctx.getBean("cacheHolder", CacheHolder.class);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = RequestUtil.resolve(request);
        if (StringUtils.isBlank(token)) {
            log.error("token必填");
            throw new BaseException(ErrorCode.UNAUTHORIZED, "token必填");
        }
        Object obj = cacheHolder.get(CacheConstants.CACHE_CERT + token);
        if (obj == null) {
            log.error("token[{}]未找到登陆凭证", token);
            throw new BaseException(ErrorCode.UNAUTHORIZED, String.format("token[%s]未找到登陆凭证", token));
        }

        Principal principal = (Principal) obj;
        Long userId = principal.getId();
        UserIdContext.setUserId(userId);
        filterChain.doFilter(request, response);
        UserIdContext.clear();
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        if(FilterUtil.ignoreMethod(request)) return true;

        final String requestUri = RequestUtil.getRelativePath(request);

        return RequestUtil.notCheck(requestUri)
                || ignores.stream().anyMatch(e->ignoresMatch.match(e, requestUri));
    }
}
